package com.zone.vehicle.superapp.view.common.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.zone.vehicle.sdk.module.superapp.vehicle.utils.NetUtil;
import com.zone.vehicle.superapp.view.SuperApplication;
import com.zone.vehicle.superapp.view.common.enums.ActionEnum;
import com.zone.vehicle.superapp.view.common.listener.ActionListener;

import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public abstract class HandledFragment extends Fragment implements IFragment {

    private static final String TAG = HandledFragment.class.getSimpleName();

    protected static List<ActionListener> listeners = new ArrayList<>();

    protected static LinkedList<String> pageList = new LinkedList<>();

    private static Activity activity;
    public NetBroadcastReceiver netBroadcastReceiver;

    public void addListener(ActionListener listener) {
        listeners.add(listener);
    }

    public void removeListener(ActionListener listener) {
        listeners.remove(listener);
    }

    public boolean onAction(ActionEnum action) {
        if (ObjectUtils.isNotEmpty(listeners)) {
            int count = 0;
            for (ActionListener listener : listeners) {
                if (listener.onAction(action)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 跳转页面（带状态）
     *
     * @param pageName
     * @return
     */
    public boolean changePage(String pageName) {
        if (change(pageName)) {
            String lastPage = getClass().getSimpleName();
            pageList.add(lastPage);
            return true;
        }
        return false;
    }

    /**
     * 返回记忆状态中指定页面，删除中间页面状态
     *
     * @param pageName
     * @return
     */
    public boolean popPage(String pageName) {
        if (ObjectUtils.isNotEmpty(pageList) && pageList.contains(pageName)) {
            while (!pageList.getLast().equals(pageName)) {
                String removePage = pageList.removeLast();
                Log.d(TAG, "removePage=" + removePage);
            }
            return change(pageList.removeLast());
        }
        return false;
    }

    public boolean onBack() {
        if (ObjectUtils.isNotEmpty(pageList)) {
            return change(pageList.removeLast());
        } else {
            finish();
        }
        return false;
    }

    protected boolean change(String pageName) {
        if (ObjectUtils.isNotEmpty(listeners)) {
            try {
                for (ActionListener listener : listeners) {
                    if (listener.onPageChanged(pageName)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "error ", e);
            }
        }
        return false;
    }

    protected abstract void finish();

    @Override
    public void initFragmentPages() {

    }

    @Override
    public void onCreate(@org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = requireActivity();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerNetListener();
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            activity.unregisterReceiver(netBroadcastReceiver);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.toString());
        }
    }

    public void showLoginFailed(String errorString) {
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (getContext() != null && getContext() != null) {
                    Toast.makeText(
                            getContext(),
                            errorString,
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void showToast(String txt) {
        Toast.makeText(
                getContext(),
                txt,
                Toast.LENGTH_LONG).show();
    }

    public abstract void showErrorPage(int type);

    public void registerNetListener() {
        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction(NetUtil.SUPER_APP_NET_WORK_CHANGED);
        netBroadcastReceiver = new NetBroadcastReceiver();
        activity.registerReceiver(netBroadcastReceiver, filter);
    }

    class NetBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
//            Log.d(TAG, "network onReceive action=" + action);
            if (action.equals(NetUtil.SUPER_APP_NET_WORK_CHANGED)) {
                int state = intent.getIntExtra(NetUtil.NETWORK_TYPE_KEY, NetUtil.NETWORK_UN_KNOW);
//                Log.w(TAG, "network onReceive super state=" + state);
                handler.sendEmptyMessage(state);
            } else {
                handler.sendEmptyMessage(NetUtil.getNetWorkState(requireContext()));
            }
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull @NotNull Message message) {
            int state = message.what;
            if (SuperApplication.NET_STATUS != state) {
                Log.w(TAG, "network handler receive state=" + state);
                SuperApplication.NET_STATUS = state;
                if (state == NetUtil.NETWORK_UN_KNOW) {
                    NetUtil.inspectNet(activity);
                } else if (state == NetUtil.NETWORK_NONE) {
                    showErrorPage(2);
                    Toast.makeText(activity, "网络未连接，请检查网络设置", Toast.LENGTH_LONG).show();
                } else {
                    showErrorPage(0);
                }
            }
            return false;
        }
    });

//    @Override
//    public void onNetChange(int netMobile) {
//        activity.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (NetUtil.inspectNet(activity)){
////                    Toast.makeText(getApplicationContext(), "网络连接正常", Toast.LENGTH_LONG).show();
//                }else {
//                    showErrorPage(2);
//                    DownloadHelper.getInstance().pauseAllTask(activity);
//                    Toast.makeText(activity, "网络未连接，请检查网络设置", Toast.LENGTH_LONG).show();
//                }
//            }
//        });
//        SuperApplication.NET_STATUS = netMobile;
//    }

}
